package gui;

import classes.Agenda;
import classes.Servidor;
import controlador.LoginControlador;
import erro.ConexaoException;
import erro.ConsultaException;
import erro.GeralException;
import fachada.Fachada;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author R
 */
public class AgendaMostrar extends javax.swing.JFrame {

    public static int id;

    /** Creates new form AgendaMostrar */
    public AgendaMostrar() {
        initComponents();
        this.setLocationRelativeTo(null);
        textObs.setEditable(false);
        textComp.setEditable(false);
        textHoraI.setEditable(false);
        textLocal.setEditable(false);
        textData.setEnabled(false);
        btSalvar.setVisible(false);
        checkStatus.setVisible(false);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        textData = new com.toedter.calendar.JDateChooser();
        textHoraI = new javax.swing.JTextField();
        try{
            javax.swing.text.MaskFormatter hora= new javax.swing.text.MaskFormatter("##:##");
            textHoraI = new javax.swing.JFormattedTextField(hora);
        }
        catch (Exception e){
        }
        textComp = new javax.swing.JTextField();
        textLocal = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        textObs = new javax.swing.JTextArea();
        jLabel9 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        jLabel12 = new javax.swing.JLabel();
        jLabel13 = new javax.swing.JLabel();
        jLabel15 = new javax.swing.JLabel();
        lbStatus = new javax.swing.JLabel();
        checkStatus = new javax.swing.JCheckBox();
        jLabel8 = new javax.swing.JLabel();
        btExcluir = new javax.swing.JButton();
        btSalvar = new javax.swing.JButton();
        btAlterar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Detalhes do Compromisso");

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setText("Data:");

        jLabel2.setText("Hora Inicial:");

        jLabel3.setText("Compromisso:");

        jLabel4.setText("Local:");

        jLabel5.setText("Observações:");

        textObs.setColumns(20);
        textObs.setFont(new java.awt.Font("Tahoma", 0, 12));
        textObs.setLineWrap(true);
        textObs.setRows(6);
        jScrollPane1.setViewportView(textObs);

        jLabel9.setText("*");

        jLabel11.setText("*");

        jLabel12.setText("*");

        jLabel13.setText("*");

        jLabel15.setText("Compromisso:");

        checkStatus.setText("Abrir Compromisso");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel4)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1)
                    .addComponent(jLabel5)
                    .addComponent(jLabel15))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(checkStatus)
                    .addComponent(lbStatus)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(textComp, javax.swing.GroupLayout.DEFAULT_SIZE, 323, Short.MAX_VALUE)
                            .addComponent(textLocal, javax.swing.GroupLayout.DEFAULT_SIZE, 323, Short.MAX_VALUE)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(textHoraI, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel11))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(textData, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel9)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel12)
                            .addComponent(jLabel13)))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 333, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1)
                    .addComponent(textData, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(textHoraI, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel11))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(textComp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel12))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(textLocal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel13))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbStatus)
                    .addComponent(jLabel15, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(checkStatus)
                .addContainerGap())
        );

        jLabel8.setText("*Campos Obrigatórios.");

        btExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/excluir.png"))); // NOI18N
        btExcluir.setText("Excluir");
        btExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btExcluirActionPerformed(evt);
            }
        });

        btSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/salvar.png"))); // NOI18N
        btSalvar.setText("Salvar");
        btSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSalvarActionPerformed(evt);
            }
        });

        btAlterar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/editar.png"))); // NOI18N
        btAlterar.setText("Alterar");
        btAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAlterarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel8)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(btSalvar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btAlterar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btExcluir, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btExcluir)
                        .addGap(18, 18, 18)
                        .addComponent(btAlterar)
                        .addGap(18, 18, 18)
                        .addComponent(btSalvar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 194, Short.MAX_VALUE)
                        .addComponent(jLabel8)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAlterarActionPerformed
        Agenda a = new Agenda();
        Fachada f = new Fachada();
        a.setAgenda_id(id);

        try {
            f.pesquisar(a);
            Servidor s = new Servidor();
            s.setMatricula(a.getLogado().getMatricula());
            s = f.pesquisarMatricula(s);
            String login = s.getLogin();
            s.setLogin(LoginControlador.login);
           // f.pesquisarLogin(s);
            if (s.getLogin().equals(login)) {
                textObs.setEditable(true);
                textComp.setEditable(true);
                textHoraI.setEditable(true);
                textLocal.setEditable(true);
                textData.setEnabled(true);
                btSalvar.setVisible(true);
                checkStatus.setVisible(true);
                if (lbStatus.getText().equals("Compromisso finalizado.")) {
                    checkStatus.setVisible(true);
                } else if (lbStatus.getText().equals("Compromisso aberto.")) {
                    checkStatus.setText("Finalizar Compromisso");
                    checkStatus.setVisible(true);
                } else {
                }
            } else {
                JOptionPane.showMessageDialog(null, "Você não tem permissão para alterar esse compromisso!");
            }

        } catch (ConexaoException ex) {
            JOptionPane.showMessageDialog(null, "Não foi possível conectar-se ao banco de dados!\n" + ex);
        } catch (ConsultaException ex) {
            JOptionPane.showMessageDialog(null, "Ocorreu um erro!\n" + ex);
        }
        // String nome = (String) tbAgenda.getValueAt(x, 5);

    }//GEN-LAST:event_btAlterarActionPerformed

    private void btSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSalvarActionPerformed
        Fachada f = new Fachada();
        if (textData.getDate() == null) {
            JOptionPane.showMessageDialog(null, "Digite uma data!");
            textData.grabFocus();
        }
        try {
            Agenda a = new Agenda();
            a.setAssunto(textComp.getText().trim());
            a.setLocal(textLocal.getText().trim());
            a.setObs(textObs.getText().trim());
            a.setData(textData.getDate());
            if (checkStatus.isSelected() && checkStatus.getText().equals("Finalizar Compromisso")) {
                a.setStatus(2);
            } else if (checkStatus.isSelected() && checkStatus.getText().equals("Abrir Compromisso")) {
                a.setStatus(1);
            } else if (!checkStatus.isSelected()) {
                if (lbStatus.getText().equals("Compromisso finalizado.")) {
                    a.setStatus(2);
                } else if (lbStatus.getText().equals("Compromisso aberto.")) {
                    a.setStatus(1);
                }
            }
            DateFormat sdfHora = new SimpleDateFormat("HH:mm");
            String hora = textHoraI.getText();
            a.setHoraI((java.util.Date) sdfHora.parse(hora));
            sdfHora.setLenient(false);
            a.setAgenda_id(AgendaMostrar.id);
            f.alterar(a);
            this.dispose();
        } catch (ConexaoException e) {
            JOptionPane.showMessageDialog(null, "Não foi possível conectar-se ao banco de dados!\n" + e);
        } catch (ConsultaException e) {
            JOptionPane.showMessageDialog(null, "Não foi possível alterar o Evento!\n" + e);
        } catch (GeralException e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
            this.repaint();
        } catch (ParseException ex) {
            JOptionPane.showMessageDialog(null, "Hora inválida!");
        }
    }//GEN-LAST:event_btSalvarActionPerformed

    private void btExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btExcluirActionPerformed
        int selectedOption = JOptionPane.showConfirmDialog(null, "Deseja realmente excluir definitivamente o Compromisso?", "Alerta!", JOptionPane.YES_NO_OPTION);
        if (selectedOption == JOptionPane.YES_OPTION) {
            Agenda a = new Agenda();
            Fachada f = new Fachada();
            a.setAgenda_id(AgendaMostrar.id);
            try {
                f.deletar(a);
                JOptionPane.showMessageDialog(null, "Compromisso excluído!");
                this.dispose();
            } catch (ConexaoException ex) {
                JOptionPane.showMessageDialog(null, "Não foi possível conectar-se ao banco de dados!\n" + ex);
            } catch (ConsultaException ex) {
                JOptionPane.showMessageDialog(null, "Não foi possível excluir o Compromisso!\n" + ex);
            }
        } else {
            this.repaint();
        }
    }//GEN-LAST:event_btExcluirActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */

        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new AgendaMostrar().setVisible(true);
            }
        });
    }

    public void carregarTabela() {
        try {
            Fachada f = new Fachada();
            Agenda a = new Agenda();
            a.setAgenda_id(AgendaMostrar.id);
            Agenda lista = f.pesquisar(a);
            DateFormat formatHora = new SimpleDateFormat("HH:mm");
            Date horaE = lista.getHoraI();
            String hora = (formatHora.format(horaE));
            if (lista.getStatus() == 2) {
                lbStatus.setText("Compromisso finalizado.");
            } else {
                lbStatus.setText("Compromisso aberto.");
            }
            textComp.setText(lista.getAssunto());
            textObs.setText(lista.getObs());
            textObs.setWrapStyleWord(true);
            textObs.setLineWrap(true);
            textData.setDate(lista.getData());
            textHoraI.setText(hora);
            textLocal.setText(lista.getLocal());
        } catch (ConexaoException ex) {
            JOptionPane.showMessageDialog(null, "Não foi possível conectar-se ao banco de dados!\n" + ex);
        } catch (ConsultaException ex) {
            JOptionPane.showMessageDialog(null, "Ocorreu um erro ao tentar carregar a tela.\n" + ex);
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btAlterar;
    private javax.swing.JButton btExcluir;
    private javax.swing.JButton btSalvar;
    private javax.swing.JCheckBox checkStatus;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lbStatus;
    private javax.swing.JTextField textComp;
    private com.toedter.calendar.JDateChooser textData;
    private javax.swing.JTextField textHoraI;
    private javax.swing.JTextField textLocal;
    private javax.swing.JTextArea textObs;
    // End of variables declaration//GEN-END:variables
}
